package com.ysucloud.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.ysucloud.api.DTO.OrderDTO;
import com.ysucloud.api.Utils.ResultVOUtil;
import com.ysucloud.api.VO.OrderDetailInfoVO;
import com.ysucloud.api.VO.OrderDetailVO;
import com.ysucloud.api.VO.OrderVO;
import com.ysucloud.api.VO.ResultVO;
import com.ysucloud.api.converter.OrderForm2OrderDTOConverter;
import com.ysucloud.api.dataobject.OrderDetail;
import com.ysucloud.api.enums.ResultEnum;
import com.ysucloud.api.exception.NullParameterException;
import com.ysucloud.api.exception.OrderException;
import com.ysucloud.api.form.OrderForm;
import com.ysucloud.api.repository.BuyerInfoRepository;
import com.ysucloud.api.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController
{
    @Autowired
    private OrderService orderService;

    @Autowired
    private BuyerInfoRepository buyerInfoRepository;

    /** 新增订单 */
    @PostMapping("/create")
    public ResultVO<Map<String,Integer>> create(@RequestBody @Validated OrderForm orderForm,
                                               BindingResult bindingResult)//递归校验
    {
        if(bindingResult.hasErrors())
        {
            log.error("【创建订单】参数不正确，orderForm={}",orderForm);
            throw new OrderException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDTO orderDTO= OrderForm2OrderDTOConverter.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList()))
        {
            log.error("【创建订单】购物车信息为空");
            throw new OrderException(ResultEnum.CART_EMPTY);
        }

        OrderDTO result=orderService.create(orderDTO);
        Map<String,Integer> map=new HashMap<>();
        map.put("orderId",result.getOrderId());
        return ResultVOUtil.success(map);
    }

    /** 查询订单列表
     * 鉴权部分在网关处
     * 1、检查用户是否存在
     * 2、返回订单列表
     */
    @PostMapping("/list")
    public ResultVO<OrderVO> list(@RequestBody JSONObject jsonObject)
    {
        Integer buyerId=jsonObject.getInteger("buyerId");
        if(StringUtils.isEmpty(buyerId)){
            throw new NullParameterException();
        }

        buyerInfoRepository.findById(buyerId).get();

        List<OrderDTO> orderDTOList= orderService.findList(buyerId);
        List<OrderVO> orderVOList = new ArrayList<>();
        for(OrderDTO orderDTO: orderDTOList)
        {
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(orderDTO,orderVO);
            orderVOList.add(orderVO);
        }
        return ResultVOUtil.success(orderVOList);
    }

    /** 查询订单详情(旧) */
    /*@PostMapping("/detail")
    ResultVO<OrderDetailVO> detail_list(@RequestBody JSONObject jsonObject)
    {
        Integer buyerId=jsonObject.getInteger("buyerId");
        Integer orderId=jsonObject.getInteger("orderId");

        if(buyerId==null || orderId == null){
            throw new NullParameterException();
        }

        List<OrderDTO> orderDTOList= orderService.findList(buyerId);
        for(OrderDTO orderDTO: orderDTOList)
        {
            if(orderDTO.getOrderId()==orderId)
            {
                orderDTO.setOrderDetailList(orderService.findOne(orderId).getOrderDetailList());
            }
        }
        OrderDetailVO orderDetailVO=new OrderDetailVO();
        for(OrderDTO orderDTO: orderDTOList)
        {
            if(orderDTO.getOrderId()==orderId)
            {
                //BeanUtils.copyProperties(orderDTO,orderDetailVO);
                orderDetailVO.setBuyerAddress(orderDTO.getBuyerAddress());
                orderDetailVO.setBuyerId(orderDTO.getBuyerId());
                orderDetailVO.setBuyerName(orderDTO.getBuyerName());
                orderDetailVO.setBuyerPhone(orderDTO.getBuyerPhone());
                orderDetailVO.setCreateTime(orderDTO.getCreateTime());
                orderDetailVO.setOrderAmount(orderDTO.getOrderAmount());
                orderDetailVO.setOrderId((orderDTO.getOrderId()));
                List<OrderDetailInfoVO> orderDetailList=new ArrayList<>();
                for(OrderDetail orderDetail: orderDTO.getOrderDetailList())
                {
                    OrderDetailInfoVO orderDetailInfoVO=new OrderDetailInfoVO();
                    orderDetailInfoVO.setDetailId(orderDetail.getDetailId());
                    orderDetailInfoVO.setOrderId(orderDetail.getOrderId());
                    orderDetailInfoVO.setProductIcon(orderDetail.getProductIcon());
                    orderDetailInfoVO.setProductId(orderDetail.getProductId());
                    orderDetailInfoVO.setProductName(orderDetail.getProductName());
                    orderDetailInfoVO.setProductPrice(orderDetail.getProductPrice());
                    orderDetailInfoVO.setProductQuantity(orderDetail.getProductQuantity());
                    orderDetailList.add(orderDetailInfoVO);
                }
                orderDetailVO.setOrderDetailList(orderDetailList);
                orderDetailVO.setUpdateTime(orderDTO.getUpdateTime());
                orderDetailVO.setOrderStatus(orderDTO.getOrderStatus());
                orderDetailVO.setPayStatus(orderDTO.getPayStatus());
            }
        }
        return ResultVOUtil.success(orderDetailVO);
    }*/

    /** 订单详情 */
    @PostMapping("/detail")
    public ResultVO<OrderDetailVO> detail_list(@RequestBody JSONObject jsonObject) {
        Integer buyerId = jsonObject.getInteger("buyerId");
        Integer orderId = jsonObject.getInteger("orderId");

        if (buyerId == null || orderId == null) {
            throw new NullParameterException();
        }

        OrderDTO orderDTO = orderService.findDetail(orderId,buyerId);

        OrderDetailVO res = new OrderDetailVO();

        BeanUtils.copyProperties(orderDTO,res);

        List<OrderDetailInfoVO> resinfo = new ArrayList<OrderDetailInfoVO>();

        for(OrderDetail orderDetail:orderDTO.getOrderDetailList()){
            OrderDetailInfoVO orderDetailInfoVO = new OrderDetailInfoVO();
            BeanUtils.copyProperties(orderDetail,orderDetailInfoVO);
            resinfo.add(orderDetailInfoVO);
        }

        res.setOrderDetailList(resinfo);

        return ResultVOUtil.success(res);
    }

    /** 取消订单 */
    @PostMapping("/cancel")
    public ResultVO cancel(@RequestBody JSONObject jsonObject) {
        Integer buyerId = jsonObject.getInteger("buyerId");
        Integer orderId = jsonObject.getInteger("orderId");
        if(buyerId == null || orderId == null){
            throw new NullParameterException();
        }

        /*boolean flag1=false;
        List<OrderDTO> orderDTOList=orderService.findList(buyerId);
        for(OrderDTO orderDTO :orderDTOList)
        {
            if (orderDTO.getOrderId()==orderId)
                flag1=true;
        }
        boolean flag2=false;
        BuyerInfo buyerInfo=buyerInfoRepository.getOne(buyerId);
        if(buyerInfo!=null)
            flag2=true;

        if(flag1&&flag2)*/
        orderService.cancel(orderId,buyerId);
        return ResultVOUtil.success(null);
    }
}
